package Dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态语句块
    static {
        //加载文件到输入流
        InputStream resourceAsStream = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        //创建Properties类的对象
        Properties p = new Properties();
        //加载流文件
        try {
            p.load(resourceAsStream);
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");
            // 加载 MySQL 驱动程序类e.printStackTrace();
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("无法加载 MySQL 驱动程序");
        }
    }

    //获取连接对象的方法
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //释放资源的方法
    public static void close(Connection conn, Statement statement, ResultSet result) {
        try {
            if (result != null) {
                result.close();
                result = null;
            }
            if (statement != null) {
                statement.close();
                statement = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
